<template>
  <f-table
    ref="tableRef"
    @register="register">
    <template #header-left>
      <el-button @click="handleBatch()">批量发放</el-button>
      <el-button @click="handleExport">{{ t("export") }}</el-button>
    </template>
    <template #username="{ row }">
      <div
        class="flex items-center cursor-pointer"
        @click="handleDetail(row)">
        <el-avatar :src="row.avatar"></el-avatar>
        <div class="ml-[5px]">
          <div class="flex items-center">
            <div class="overflow-hidden nickname line-height-[16px]">{{ row.nickname }}</div>
            <el-icon
              class="ml-[5px]"
              @click.stop="copyEvent(row.nickname)"
              ><CopyDocument
            /></el-icon>
          </div>
          <div class="text-[12px] text-[#999] timer">{{ row.reg_time || '' }}</div>
        </div>
      </div>
    </template>
    <template #time_length="{ row }">
      <el-link
        type="primary"
        @click="handleShowLog(row)"
        >{{ format(row.time_length) }}</el-link
      >
    </template>
    <template #is_over="{ row }">
      <el-tag
        v-if="row.is_over === 1"
        type="success">
        已完播
      </el-tag>
      <el-tag
        v-else
        type="primary">
        未完播
      </el-tag>
    </template>
    <template #wanbo_times="{ row }">
      <span>答:{{ row.dati_num }} / </span>
      
      <span :style="{color: (row.dati_num && !row.is_right) ? 'red' : ''}">对:{{ row.is_right }}</span>
      
    </template>
    <template #hongbao_status="{ row }">
      <el-popover effect="light" trigger="hover" placement="top" width="auto">
        <template #default>
          <div v-if="!([0,-1].includes(row.hongbao_status))">
            <div>订单号: {{ row.hongbao_ordersn || '' }}</div>
            <div>微信交易单号: {{ row.hongbao_wxorderid || '' }}</div>
          </div>
          <div v-if="[0,-1,2].includes(row.hongbao_status)">失败原因: {{ row.hongbao_msg || '' }}</div>
        </template>
        <template #reference>
          <el-tag
            v-if="row.hongbao_status === 1"
            type="success">
            已领取
          </el-tag>
          <el-tag
            v-if="row.hongbao_status === 2"
            type="error">
            发放失败
          </el-tag>
          <el-tag
            v-if="row.hongbao_status === 3"
            type="warning">
            待领取
          </el-tag>
           <el-tag
            v-else
            type="info">
            未获得
          </el-tag>
        </template>
      </el-popover>
    </template>
    <template #money="{ row }">
      <div class="flex items-center">
        <span :class="getStatusClass(row.hongbao_status)">
          {{ row.money }}
          <template v-if="row.hongbao_status == 2">
            <el-tooltip :content="row.hongbao_msg || '无异常信息'">
              <el-icon class="ml-[5px] cursor-pointer"><Warning /></el-icon>
            </el-tooltip>
          </template>
        </span>
      </div>
    </template>
    <template #action="{ row }">
      <el-button
        type="primary"
        text
        @click="handleShowLog(row)"
        >观看日志</el-button
      >
      <el-button
        v-if="row.hongbao_status == 2"
        type="primary"
        text
        @click="handleBatch(row)"
        >重新发放</el-button
      >
    </template>
  </f-table>
  <f-detail-drawer
    ref="detailDrawerRef"
    is="UserDetail"></f-detail-drawer>
  <f-form-model
    ref="formModelRef"
    is="UserViewData"
    width="800px"
    :showFooter="false"></f-form-model>
</template>
<script lang="ts" setup>
// 获取红包状态对应的CSS类
const getStatusClass = (status: number): string => {
  switch (status) {
    case -1:
      return 'text-info';
    case 0:
      return 'text-primary';
    case 1:
      return 'text-success';
    case 2:
    case 3:
      return 'text-danger';
    default:
      return '';
  }
}
import { computed, onMounted, ref, watch } from "vue";
import { t } from "@/lang";
import FTable, {
  BasicColumn,
  useTable,
} from "@/addon/htscrm/components/f-table";
import {
  tableColumns,
  tableSearchFormItems,
} from "@/addon/htscrm/data/activity.video.user-data";
import {
  exportDataApi,
  getActivityAnalysisDataApi,
  getStoreAllApi,
  resendApi,
} from "@/addon/htscrm/api";
import FDetailDrawer from "@/addon/htscrm/components/f-detail-drawer";
import FFormModel from "@/addon/htscrm/components/f-form-model";
import { CopyDocument, Warning } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useClipboard } from "@vueuse/core";
import { useRouter } from "vue-router";

const router = useRouter();

const prop = defineProps({
  searchForm: {
    type: Object,
    default: () => ({}),
  },
});

const formModelRef = ref();
const detailDrawerRef = ref();
const tableRef = ref();
const { methods, register } = useTable({
  rowKey: "id",
  immediate: false,
  searchFromItems: tableSearchFormItems(t),
  columns: tableColumns(t) as BasicColumn<IActivityItem>[],
  beforeFetch: (opt) => {
    return {
      ...opt,
      ...prop.searchForm,
      search_key: opt.search_key.value,
      search_type: opt.search_key.select,
    };
  },
  api: async (opt) => (await getActivityAnalysisDataApi(opt)).data,
});

const searchFromItems = tableSearchFormItems(t);
async function getStoreList() {
  const res = await getStoreAllApi();

  searchFromItems[2].childrenComponent.children = res.data.map((item) => {
    return {
      label: item.title,
      value: item.id,
    };
  });
  methods.setFormItems(searchFromItems);
}

function handleDetail(row: IUserItem) {
  detailDrawerRef.value?.show("客户详情", row);
}

async function handleBatch(row?: IUserItem) {
  const selection: IUserItem[] = row ? [row] : methods.getSelectionRows();
  // selection
  const ids: number[] = selection
    .filter((item) => item.hongbao_status === 2)
    .map((item) => item.id as number);

  if (ids.length === 0) {
    ElMessage.warning("没有可重新发红包的用户，清重新选择");
    return;
  }

  const activityId = prop.searchForm.id as number;
  const action = await ElMessageBox.alert(
    "确认要发放选中用的红包吗?",
    "系统提示",
    {
      type: "warning",
      showCancelButton: true,
      cancelButtonText: "取消",
      confirmButtonText: "确定",
    }
  );

  if (action === "confirm") {
    const params = {
      id: activityId,
      uids: ids,
    };
    await resendApi(params);
    ElMessage.success("发放成功");
    methods.reload();
  }
}

function reload() {
  console.log(111);

  // getStoreList()
  methods.reload();
}

/**
 * @description 导出
 */
async function handleExport() {
  let params = methods.getSearchInfo()
  const res = await exportDataApi("activityUser", {
    ...params,
    ...prop.searchForm,
    search_key: params.search_key.value,
    search_type: params.search_key.select,

  });
  if (res.data) {
    const action = await ElMessageBox.confirm(
      "文件导出已添加到下载中心，是否立即前往下载中心",
      t("alert.title"),
      {
        cancelButtonText: "我再看看",
        confirmButtonText: "立即前往",
      }
    );
    console.log(action);

    if (action === "confirm") {
      router.push("/htscrm/system/download");
    }
  }
}

function format(val: number) {
  const m = parseInt(val / 60 + "");
  const s = val % 60;
  return `${m}分${s}秒`;
}

// 复制
const { copy, isSupported, copied } = useClipboard();
const copyEvent = (text: string) => {
  if (!isSupported.value) {
    // ElMessage({
    //     message: t('notSupportCopy'),
    //     type: 'warning'
    // })
  }
  copy(text);
};

watch(copied, () => {
  if (copied.value) {
    ElMessage({
      message: t("copySuccess"),
      type: "success",
    });
  }
});

function handleShowLog(row: IUserItem) {
  formModelRef.value?.show("观看日志", row, prop.searchForm.id);
}

onMounted(() => {
  getStoreList();
});

defineExpose({
  reload,
});
</script>

<style lang="scss" scoped>
:deep(.f-search) {
  background-color: var(--el-bg-color-page);
}
.el-button.is-text {
  margin-left: 0 !important;
}

.el-avatar {
  width: 40px;
  height: 40px;
}
.nickname {
  max-width: 85px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 20px;
}
.timer{
  line-height: 16px;
}
</style>
